<script lang="ts" setup>
import * as Yup from 'yup'

defineOptions({
  name: 'LoginForget',
})
definePageMeta({
  layout: 'other',
})
const router = useRouter()
const { countryCallingCode } = useIpApi()
const areaCode = ref(countryCallingCode.value)
const { areaCodeOptionsFiltered } = useAreaCode()

const isPhoOrEma = ref<'p' | 'e'>('e')
const account = ref('')
const isPop = ref(false)

const schema = Yup.object().shape({
  account: Yup.string(),
})
const curAccount = computed(() => isPhoOrEma.value == 'e' ? account.value : `${areaCode.value}-${account.value}`)
const curExistsTy = computed(() => isPhoOrEma.value == 'e' ? 2 : 3)

/** 发送手机验证码 */
const { runAsync: runAsyncSendPhoneSms, loading: phoneCaptchaLoading } = useRequest(
  () => ApiMemberPhoneSms({ phone: curAccount.value, type: 0 }),
  {
    onSuccess() {
      message.success($t('success_send_code'))
      i18nNavigateTo({ path: '/login/verify', query: { t: 'p', n: curAccount.value } })
    },
  },
)
/** 发送邮箱验证码 */
const {
  runAsync: runAsyncMemberSendMailCaptcha,
  loading: emailCaptchaLoading,
} = useRequest(() => ApiMemberSendMailCaptcha({ email: curAccount.value }), {
  onSuccess() {
    message.success($t('success_send_code'))
    i18nNavigateTo({ path: '/login/verify', query: { t: 'e', n: curAccount.value } })
  },
})
/** 检测是否存在 */
const { runAsync: runExists, loading: existLoading } = useRequest(ApiMemberExists, {
  onSuccess() {
    message.error($t('no_this_user'))
  },
  onError: () => {
    if (isPhoOrEma.value == 'e') {
      runAsyncMemberSendMailCaptcha()
    }
    else {
      runAsyncSendPhoneSms()
    }
  },
})
const isLoading = computed(() => phoneCaptchaLoading.value || emailCaptchaLoading.value || existLoading.value)

async function isWhat(value: string) {
  account.value = value
  if (value.length < 3) {
    isPhoOrEma.value = 'e'
    return
  }
  if (numberReg.test(value)) {
    isPhoOrEma.value = 'p'
  }
  else {
    isPhoOrEma.value = 'e'
  }
}
function onBack() {
  router.back()
}
function goLogin() {
  i18nNavigateTo('/login/signin')
}

function onValidNum() {
  let res = ''
  if (isPhoOrEma.value === 'e') {
    res = validEmailVal(account.value) as string
  }
  else {
    res = validPhoneVal(account.value)
  }
  if (res) {
    return res
  }
}
function validEmailVal(value: string) {
  const lastDotIdx = value ? value.lastIndexOf('.') : -1
  let result
  if (!value)
    result = $t('pop_up_create_account_no_support_email')
  else if (!value.includes('@'))
    result = $t('pop_up_create_account_email_add_char', { delta: '@' })
  else if (!value.includes('.'))
    result = $t('pop_up_create_account_no_dot_email_add_char', { delta: '.' })
  else if (lastDotIdx === value.length - 1)
    result = $t('pop_up_create_account_no_support_email')
  else if (!emailReg.test(value))
    result = $t('pls_input_email')
  else if (value && value.length > 30)
    result = $t('pls_input_email')
  else result = ''

  // 请在您的电邮地址中加入 “@” 符号
  // 请在您的电邮地址中加入 “.” 符号
  // 电子邮件域不受支持
  // 请输入有效的电邮地址
  return result
}

function validPhoneVal(value: string) {
  let result
  if (areaCode.value === '+63') {
    result
        = philippinePhoneReg.test(`+63${value}`) && value.length > 5 && value.length <= 18
        ? ''
        : $t('phone_invalid')
  }
  else if (areaCode.value === '+86') {
    result
        = chinaPhoneReg.test(`${value}`) && value.length > 5 && value.length <= 18
        ? ''
        : $t('phone_invalid')
  }
  else if (areaCode.value === '+55') {
    result
        = brazilPhoneReg.test(`+55${value}`) && value.length > 5 && value.length <= 18
        ? ''
        : $t('phone_invalid')
  }
  else {
    result
        = numberReg.test(value) && value.length > 5 && value.length <= 18 ? '' : $t('phone_invalid')
  }
  return result
}
function onSubmit(values: any) {
  const res = onValidNum()
  if (res) {
    message.error(res)
    return
  }
  runExists({ ty: curExistsTy.value, val: values.account, noNotify: true })
}
</script>

<template>
  <div class="h-full">
    <div class="size-full bg-[#232626]">
      <div class="relative w-full">
        <BaseImage url="/images/webp/header/h5-header.png" alt="" loading="eager" class="w-full aspect-[414/237]" />
        <div class="absolute top-0 w-full flex justify-between items-center px-6 py-3">
          <div>logo</div>
          <BaseButton class="w-7 !h-7 bg-[rgba(255,255,255,.05)] rounded" type="none" @click="onBack">
            <BaseIcon name="uni-close2" class="text-xl scale-50" />
          </BaseButton>
        </div>
      </div>

      <div class="py-5 px-6 relative w-full">
        <div class="flex justify-between w-full mb-3">
          <span class="text-base font-extrabold">{{ $t('reset_password') }}</span>
        </div>
        <div class="mb-3">
          <BaseForm :schema="schema" @submit="onSubmit">
            <BaseInput
              name="account"
              required
              class="mb-3"
              :placeholder="$t('emailOrPhone')"
              @update:model-value="isWhat"
            >
              <template v-if="isPhoOrEma == 'p'" #left-icon>
                <BaseButton type="none" class="text-[0.75rem] !p-0" @click="() => isPop = true">
                  <div class="border-r-[2px] border-[#e4eaf019] pr-1 flex">
                    {{ areaCode }}<BaseIcon name="uni-arrow-down" class="pl-1" />
                  </div>
                </BaseButton>
              </template>
            </BaseInput>
            <BaseButton
              html-type="submit"
              type="primary"
              class="w-full text-xs h-10"
              :loading="isLoading"
            >
              {{ $t('reset_password') }}
            </BaseButton>
          </BaseForm>
        </div>
        <div class="center mt-4 font-extrabold text-[#B3BEC1]" @click="goLogin">
          <BaseIcon name="uni-arrow-down" class="text-base mr-.5 rotate-90" />{{ $t('return_login') }}
        </div>
      </div>
    </div>
    <BaseBob v-model:show="isPop" v-model:selected="areaCode" is-search :need-move="true" :header="$t('area_choice')" :option="areaCodeOptionsFiltered" />
  </div>
</template>

<style lang="scss" scoped></style>
